class EventManager {
  private _eventCenter: Map<string, Array<{ func: Function; ctx: unknown }>> = new Map()

  on(eventName: string, func: Function, ctx?: unknown) {
    if (this._eventCenter.has(eventName)) {
      this._eventCenter.get(eventName).push({ func, ctx })
    } else {
      this._eventCenter.set(eventName, [{ func, ctx }])
    }
  }

  off(eventName: string, func: Function) {
    if (this._eventCenter.has(eventName)) {
      const index = this._eventCenter.get(eventName).findIndex(i => i.func === func)
      index > -1 && this._eventCenter.get(eventName).splice(index, 1)
    }
  }

  emit(eventName: string, ...params: any[]) {
    if (this._eventCenter.has(eventName)) {
      this._eventCenter.get(eventName).forEach(({ func, ctx }) => {
        ctx ? func.apply(ctx, params) : func(...params)
      })
    }
  }
}

export default new EventManager()
